package ru.surfstudio.graduate.data;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;


public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

	private static final String DATABASE_NAME = "rss_reader.db";
	private static final int DATABASE_VERSION = 3;
	
	private Dao<Channel, Integer> channelDao;
	private Dao<Feed, Integer> feedDao;
	
	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}
	
	@Override
	public void onCreate(SQLiteDatabase sqLiteDb, ConnectionSource conSource) {
		try {
			TableUtils.createTable(conSource, Channel.class);
			TableUtils.createTable(conSource, Feed.class);
			
		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Unable to create datbases", e);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase sqLiteDb, ConnectionSource conSource, int oldVer,
			int newVer) {
		try {
			TableUtils.dropTable(conSource, Channel.class, true);
			TableUtils.dropTable(conSource, Feed.class, true);
			onCreate(sqLiteDb, conSource);

		} catch (SQLException e) {
			Log.e(DatabaseHelper.class.getName(), "Unable to upgrade database from version " + 
					oldVer + " to new " + newVer, e);
		}
	}

	public Dao<Channel, Integer> getChannelDao() throws SQLException {
		if (channelDao == null) {
			channelDao = getDao(Channel.class);
		}
		return channelDao;
	}

	public Dao<Feed, Integer> getFeedDao() throws SQLException {
		if (feedDao == null) {
			feedDao = getDao(Feed.class);
		}
		return feedDao;
	}
	
}